<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" size="large" :inline="true" v-show="showSearch" label-width="78px">
      <el-form-item label="名称" prop="fullName">
        <el-input @blur="handleQuery" v-model="queryParams.fullName" placeholder="请输入" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="型号" prop="modal">
        <el-input @blur="handleQuery" v-model="queryParams.modal" placeholder="请输入" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="入库日期" prop="storeDate">
        <el-date-picker @change="handleQuery" v-model="queryParams.storeDate" value-format="YYYY-MM-DD" type="daterange"
          range-separator="To" start-placeholder="起始日期" end-placeholder="截止日期" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="success" :disabled="!(userStore.name == 'wuzg')" icon="Search"
          @click="openLog">操作记录</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['project:goods:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['project:goods:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['project:goods:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['project:goods:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table border v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column label="型号" align="center" prop="modal" />
      <el-table-column label="完整名称" align="center" prop="fullName" />
      <el-table-column label="简称" align="center" prop="name" />
      <!-- <el-table-column label="历史采购平均价(￥)" align="center" prop="avgCost">
        <template #default="scope">
          <span :style="{ color: '#008c46', fontWeight: '500' }">{{ scope.row.avgCost }}</span>
        </template>
</el-table-column> -->
      <el-table-column label="历史采购最低价(￥)" align="center" prop="minPrice">
        <template #default="scope">
          <span :style="{ color: '#008c46', fontWeight: '500' }">{{ scope.row.minPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="历史采购明细(默认自2019年9月至今)" align="center" prop="historyCostList" min-width="250">
        <template #default="scope">
          <div v-for="(item, index) in scope.row.historyCostList" :key="index" class="record-item">
            <span class="batch">第{{ item.index }}批</span>
            <span class="batch">数量:{{ item.count }}</span>
            <span class="price-label">入库价格:</span>
            <strong class="price-value">{{ item.price }}</strong>
            <span class="date-label">入库日期:</span>
            <strong :style="{ color: '#E6A23C' }">{{ item.date }}</strong>
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="库存余量" align="center" prop="remaining" /> -->

      <el-table-column label="库存余量(全部时间)" align="center">
        <template #default="scope">
          <span :style="{
            color: scope.row.remaining < 0 ? 'red' :
              scope.row.remaining > 0 ? 'green' : '#000',
            fontWeight: 'bold',
            fontSize: '14px'  // 可根据需要调整，比如 16px 加大
          }">
            {{ scope.row.remaining }}
          </span>
        </template>
      </el-table-column>


      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['project:goods:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['project:goods:remove']">删除</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
        </template>
</el-table-column> -->
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改货物对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="goodsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="id" prop="id">
          <el-input v-model="form.id" placeholder="请输入id" />
        </el-form-item>
        <el-form-item label="型号" prop="modal">
          <el-input v-model="form.modal" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="完整名称" prop="fullName">
          <el-input v-model="form.fullName" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="简称" prop="name">
          <el-input v-model="form.name" placeholder="请输入简称" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item>
        <el-form-item label="最后登录IP" prop="loginIp">
          <el-input v-model="form.loginIp" placeholder="请输入最后登录IP" />
        </el-form-item>
        <el-form-item label="最后登录时间" prop="loginDate">
          <el-date-picker clearable v-model="form.loginDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择最后登录时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>


  <el-drawer v-model="operDrawer" title="操作记录" :with-header="false" size="50%">
    <logIndex></logIndex>
  </el-drawer>

</template>

<script setup name="Goods">
import { listGoods, getGoods, delGoods, addGoods, updateGoods } from "@/api/project/goods";
import { ref } from "vue";
import logIndex from '../operLog/index.vue'

import useUserStore from '@/store/modules/user'
const userStore = useUserStore()

const { proxy } = getCurrentInstance();

const goodsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const operDrawer = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    modal: null,
    fullName: null,
    name: null,
    storeDate: []
  },
  rules: {
    id: [
      { required: true, message: "id不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询货物列表 */
function getList() {
  loading.value = true;
  listGoods(queryParams.value).then(response => {
    goodsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    modal: null,
    fullName: null,
    name: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    loginIp: null,
    loginDate: null
  };
  proxy.resetForm("goodsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


//查看操作记录
function openLog() {
  operDrawer.value = true
}



/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加货物";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getGoods(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改货物";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["goodsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateGoods(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGoods(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除货物编号为"' + _ids + '"的数据项？').then(function () {
    return delGoods(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('project/goods/export', {
    ...queryParams.value
  }, `goods_${new Date().getTime()}.xlsx`)
}

getList();
</script>


<style scoped>
.record-item {
  display: flex;
  gap: 8px;
  align-items: center;
  font-size: 14px;
  margin-bottom: 4px;
  flex-wrap: wrap;
}

.batch {
  color: #1890ff;
  font-weight: 500;
}

.price-label {
  color: #333;
}

.price-value {
  color: #d4380d;
  /* 红色，突出价格数值 */
  font-weight: bold;
}

.date {
  color: #333;
  font-size: 14px;
}
</style>
